package com.fd.fdsso.web.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fd.dao.base.common.Condition;
import com.fd.dao.base.common.Operators;
import com.fd.fdsso.pojo.SSOUserInfo;
import com.fd.fdsso.pojo.SSOUserLogin;
import com.fd.fdsso.service.ILoginService;
import com.fd.fdsso.utils.SSoUtils;
import com.fd.fdsso.vo.MessageVo;
import com.fd.fdsso.vo.ParameterVo;
import com.fd.util.MyUtils;
import com.lizeng.utils.MyDigestUtils;

/***
 * 处理用户登录
 * 
 * @author 符冬
 * 
 */
@Controller
public class LoginAction {
	@Resource
	private ILoginService loginService;

	/**
	 * 准备登录信息
	 * 
	 * @return
	 */
	@RequestMapping("login")
	public String login(HttpServletRequest req) {
		String loginId = MyUtils.getCookieValue(req, SSoUtils.CK_LOGINID);
		String loginName = MyUtils.getCookieValue(req, SSoUtils.CK_LOGINNAME);
		try {
			loginName=URLDecoder.decode(loginName, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String signCode = MyUtils.getCookieValue(req, SSoUtils.CK_SIGNCODE);
		String ckMail = MyUtils.getCookieValue(req, SSoUtils.CK_MAIL);
		if (MyUtils.isNotEmpty(signCode)
				&& MyUtils.isNotEmpty(loginName)
				&& MyUtils.isNotEmpty(loginId)
				&& MyDigestUtils.shaDigest(loginName + loginId,
						SSoUtils.SSO_RB.getString("SIGN_KEY")).equals(signCode)) {
			// 名
			req.setAttribute("idname", SSoUtils.SSO_RB.getString("LOGIN_ID"));
			req.setAttribute("nmname", SSoUtils.SSO_RB.getString("LOGIN_NAME"));
			req.setAttribute("signname",
					SSoUtils.SSO_RB.getString("SSO_SIGNATURE"));
			req.setAttribute("mailname",
					SSoUtils.SSO_RB.getString("LOGIN_EMAIL"));

			// 值
			req.setAttribute("idv", loginId);
			req.setAttribute("namev", loginName);
			req.setAttribute("signv", signCode);
			req.setAttribute("mailv", ckMail);
			return "postUrl";
		} else {
			String url = MyUtils.getStringParameter(req, "url");
			req.setAttribute("url", url);
			return "login";
		}
	}

	/**
	 * 开始登录
	 * 
	 * @return
	 */
	@RequestMapping("loginValidate")
	public String loginValidate(HttpServletRequest req,
			HttpServletResponse res, SSOUserLogin user) {
		if (MyUtils.isNotEmpty(user.getUserName())
				&& MyUtils.isNotEmpty(user.getUserPwd())) {
			SSOUserLogin ulogin = loginService
					.getUsersDao()
					.get(MyUtils.getConditions(
							new Condition("userPwd", Operators.EQ,
									MyDigestUtils.shaDigest(user.getUserPwd())),
							new Condition("userName", Operators.EQ, user
									.getUserName())));

			String url = MyUtils.getStringParameter(req, "url");
			if(!MyUtils.isNotEmpty(url)){

				req.setAttribute("m",
						new MessageVo("服务器拒绝登录", "访问来路不明，未授权", "login.do"));
				return "common/message";
			
			}
			url = MyDigestUtils.decode64(url);
			if (url.indexOf("?") != -1 && url.indexOf("=") != -1) {
				String[] arr = url.split("\\?");
				String[] yuarr = arr[1].split("&");
				List<ParameterVo> vos = new ArrayList<ParameterVo>();
				for (String s : yuarr) {
					ParameterVo vo = new ParameterVo();
					String[] ar = s.split("=");
					vo.setName(ar[0]);
					vo.setValue(ar[1]);
					vos.add(vo);
				}
				req.setAttribute("vos", vos);
				req.setAttribute("url", arr[0]);
			}else{
				req.setAttribute("url", url);
			}
			// 远程参数
			String code = SSoUtils.getLoginCode(ulogin);
			req.setAttribute("idv", ulogin.getLoginId());
			req.setAttribute("idname", SSoUtils.SSO_RB.getString("LOGIN_ID"));
			req.setAttribute("nmname", SSoUtils.SSO_RB.getString("LOGIN_NAME"));
			req.setAttribute("namev", ulogin.getUserName());
			req.setAttribute("signname",
					SSoUtils.SSO_RB.getString("SSO_SIGNATURE"));
			req.setAttribute("signv", code);
			req.setAttribute("mailname",
					SSoUtils.SSO_RB.getString("LOGIN_EMAIL"));
			req.setAttribute("mailv", ulogin.getEmail());
			// 本机cookie
			MyUtils.addCookie(res, SSoUtils.CK_LOGINID, ulogin.getLoginId()
					.toString());
			try {
				String nameec= URLEncoder.encode(ulogin.getUserName(),"utf-8");
				MyUtils.addCookie(res, SSoUtils.CK_LOGINNAME,nameec);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			MyUtils.addCookie(res, SSoUtils.CK_MAIL, ulogin.getEmail());
			MyUtils.addCookie(res, SSoUtils.CK_SIGNCODE, code);

			return "postUrl";
		} else {
			req.setAttribute("m",
					new MessageVo("登录信息填写不全", "请重新登录", "login.do"));
			return "common/message";
		}
	}

	/**
	 * 注册界面
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("regUI")
	public String regUI(HttpServletRequest req) {
		return "reg";
	}

	/**
	 * 用户注册
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("reg")
	public String reg(HttpServletRequest req, SSOUserLogin uu) {
		if (MyUtils.isNotEmpty(uu.getUserName())
				&& MyUtils.isNotEmpty(uu.getEmail())
				&& MyUtils.isNotEmpty(uu.getUserPwd())) {
			uu.setUserPwd(MyDigestUtils.shaDigest(uu.getUserPwd()));
			SSOUserInfo info = new SSOUserInfo();
			info.setRegIp(MyUtils.getUserIp(req));
			try {
				loginService.saveUser(uu, info);
				req.setAttribute("m",
						new MessageVo("注册成功", "请直接登录", "login.do"));
			} catch (Exception e) {
				req.setAttribute("m",
						new MessageVo("注册失败", "请重新注册", "regUI.do"));
				e.printStackTrace();
			}
		} else {
			req.setAttribute("m", new MessageVo("注册失败", "注册信息填写不完整，请重新填写",
					"regUI.do"));
		}
		return "common/message";
	}

}
